package listbyorder.access101_200.test144;

import listbyorder.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/12 8:52
 */
public class Solution3 {

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        TreeNode c1 = root;
        TreeNode c2 = null;
        while (c1 != null) {
            c2 = c1.left;
            if (c2 != null) {
                while (c2.right != null && c2.right != c1) {
                    c2 = c2.right;
                }
                if (c2.right == null) {
                    c2.right = c1;
                    res.add(c1.val);
                    c1 = c1.left;
                    continue;
                }
                if (c2.right == c1) {
                    c2.right = null;
                }
            } else {
                res.add(c1.val);
            }
            c1 = c1.right;
        }
        return res;
    }
}
